<template>
  <!-- 企业 认证 -->
  <view>
    <baseHead :title="title" :showReturn="true"></baseHead>

    <u-alert title="认证中" type="primary" v-if="form.State === 0"></u-alert>
    <u-alert
      title="认证成功"
      type="primary"
      v-else-if="form.State === 1"
    ></u-alert>
    <u-alert
      :title="'认证失败:' + form.CheckReason"
      type="primary"
      v-else-if="form.State === 2"
    ></u-alert>
    <u-alert
      title="您所提供的信息将被保密，仅供认证审核使用"
      type="primary"
      v-else
    ></u-alert>

    <view class="box">
      <view class="content">
        <u-form :model="form" ref="uForm">
          <u-form-item
            label="企业名称"
            label-width="100"
            required
            style="padding: 10rpx 40rpx"
          >
            <view style="width: 100%">
              <u--input
                style="background-color: #fff"
                :disabled="form.State === 1"
                placeholder="企业名称"
                v-model="form.FullName"
                input-align="right"
                border="none"
                :adjustPosition="false"
              >
              </u--input>
            </view>
          </u-form-item>

          <u-form-item
            label="注册地址"
            label-width="100"
            required
            style="padding: 10rpx 40rpx"
          >
            <view style="width: 100%">
              <pick-regions
                v-if="!form.State"
                @getRegion="handleGetRegion"
                :defaultRegion="defaultRegion"
              >
                <view style="display: flex">
                  <u--input
                    v-model="city"
                    disabled
                    disabledColor="#ffffff"
                    placeholder="请选择"
                    inputAlign="right"
                    border="none"
                  >
                  </u--input>
                  <u-icon name="arrow-right"></u-icon>
                </view>
              </pick-regions>
              <view style="display: flex; width: 100%" v-else>
                <u--input
                  v-model="city"
                  disabled
                  disabledColor="#ffffff"
                  placeholder="请选择"
                  inputAlign="right"
                  border="none"
                  :adjustPosition="false"
                >
                </u--input>
                <u-icon name="arrow-right"></u-icon>
              </view>
            </view>
          </u-form-item>

          <u-form-item
            label="详细地址"
            label-width="100"
            required
            style="padding: 10rpx 40rpx"
          >
            <view
              style="
                width: 100%;
                text-align: right;
                display: flex;
                justify-content: flex-end;
                color: #c0c4cc;
              "
              @click="xxAddress"
              v-if="!form.State"
            >
              {{ form.Address || "详细地址" }}
              <u-icon name="arrow-right"></u-icon>
            </view>
            <view
              v-else
              style="
                text-align: right;
                display: flex;
                justify-content: flex-end;
                flex: 1;
              "
            >
              {{ form.Address || "详细地址" }}
              <u-icon name="arrow-right"></u-icon>
            </view>
          </u-form-item>

          <u-form-item
            label="联系人名字"
            label-width="100"
            required
            style="padding: 10rpx 40rpx"
          >
            <view style="width: 100%">
              <u-input
                style="background-color: #fff"
                :disabled="form.State === 1"
                placeholder="联系人名字"
                v-model="form.ContactName"
                input-align="right"
                border="none"
                :adjustPosition="false"
              />
            </view>
          </u-form-item>

          <u-form-item
            label="证件证号"
            label-width="100"
            style="padding: 10rpx 40rpx"
          >
            <view style="width: 100%">
              <u-input
                style="background-color: #fff"
                :disabled="form.State === 1"
                placeholder="请填写证件号码"
                v-model="form.ContactIdCard"
                input-align="right"
                border="none"
                :adjustPosition="false"
              />
            </view>
          </u-form-item>

          <u-form-item
            label="联系人手机号"
            label-width="100"
            required
            style="padding: 10rpx 40rpx"
          >
            <view style="width: 100%">
              <u-input
                style="background-color: #fff"
                :disabled="form.State === 1"
                placeholder="联系人手机号"
                v-model="form.ContactPhone"
                input-align="right"
                border="none"
                :adjustPosition="false"
              />
            </view>
          </u-form-item>
          <!-- 				<u-form-item v-if="!form.State" label="验证码" label-width="100" required style="padding: 10rpx 40rpx">
						<view style="width: 100%; display: flex; align-items: center">
							<u-input placeholder="请输入验证码" v-model="form.yzma" input-align="right" border="none" />
							<text style="margin-left: 20rpx" @click="yanzhengma"> 获取验证码</text>
							<u-code ref="uCode" @change="codeChange" seconds="20" @start="disabled1 = true"
								@end="disabled1 = false">
							</u-code>
						</view>
					</u-form-item> -->

          <u-form-item
            label="验证码"
            label-width="100"
            v-if="!form.State"
            prop="yzmm"
            ref="item1"
            required
            style="padding: 10rpx 40rpx; width: "
            :borderBottom="false"
          >
            <view style="width: 100%">
              <!-- #ifndef APP-NVUE -->
              <u-input
                v-model="form.yzma"
                border="none"
                placeholder="请输入验证码"
                :adjustPosition="false"
              >
                <!-- #endif -->
                <!-- #ifdef APP-NVUE -->
                <u-input
                  v-model="form.yzma"
                  border="none"
                  placeholder="请输入验证码"
                  :adjustPosition="false"
                >
                  <!-- #endif -->
                  <template slot="suffix">
                    <u-button
                      @tap="yanzhengma"
                      :text="tips"
                      type="success"
                      size="mini"
                      :disabled="disabled1"
                    ></u-button>
                  </template>
                  <!-- #ifndef APP-NVUE -->
                </u-input>
                <!-- #endif -->
                <!-- #ifdef APP-NVUE -->
              </u-input>
              <!-- #endif -->
            </view>
          </u-form-item>
          <u-code
            ref="uCode"
            @change="codeChange"
            seconds="60"
            @start="disabled1 = true"
            @end="disabled1 = false"
          >
          </u-code>
          <u-form-item
            label="上传营业执照"
            label-width="100"
            required
            style="padding: 10rpx 40rpx"
          >
            <view style="width: 100%">
              <view class="pre-box">
                <!-- 	<view class="pre-item" v-for="item in fileList2" :key="item.url"
									v-show="fileList2.length > 0">
									<image class="pre-item-image" :src="item.url" mode="aspectFill">
									</image>
								</view> -->
                <view class="pre-item">
                  <u-upload
                    :deletable="!form.State"
                    @afterRead="afterRead"
                    :previewFullImage="true"
                    accept="image"
                    class="pre-item-image"
                    :maxCount="1"
                    :uploadIconColor="uploadIconColor"
                    @delete="deletePic"
                    :fileList="fileList2"
                  >
                  </u-upload>
                </view>
              </view>
            </view>
          </u-form-item>
        </u-form>
      </view>
      <view class="but" v-if="!form.State">
        <view @click="clicktijiao" class="tijiao">提交</view>
        <!-- <u-button type="primary" >提交</u-button> -->
      </view>
    </view>

    <addPopup
      :show.sync="addShow"
      v-if="addShow"
      :addTitle="addTitle"
      :addxxAddressItem="addxxAddressItem"
      @editAddress="editAddress"
    ></addPopup>
  </view>
</template>

<script>
import baseHead from "@/pages/component/baseHead.vue";
import pickRegions from "@/pages/component/pick-regions/pick-regions.vue";
import addPopup from "@/pages/component/addPopup/index.vue";
export default {
  data() {
    return {
      title: "企业认证",
      form: {
        Address: "",
        ProvinceCode: "",
        CityCode: "",
        AreaCode: "",
        FullName: "",
        ContactName: "",
        ContactPhone: "",
        yzma: "",
        ContactIdCard: "",
        FullAddress: "",
        License: "",
        Latitude: "0",
        Longitude: "0",
      },

      Latitude: "",
      Longitude: "",

      selRegion: "", //选择的省市区
      filter: ["重庆市", "上海市", "天津市", "北京市"],
      defaultRegion: ["", "", ""],
      city: "",
      isSel: false, //是否是选择
      tips: "",
      fileList2: [],
      disabled1: false,
      uploadIconColor: "#D3D4D6",

      // 图片访问路径
      srcinge: this.$config.domain.staticUrl,

      typeyd: "",
      addShow: false, //控制子组件显示隐藏
      addTitle: "详细地址",
      addxxAddressItem: {},
    };
  },
  components: {
    baseHead,
    pickRegions,
    addPopup,
  },
  onShow() {},
  // 监听页面加载，其参数为上个页面传递的数据
  onLoad(option) {
    this.getLocationdw();
    if (option.ids) {
      this.cxrzxx(option.ids);
    }
    if (option.type) {
      this.typeyd = option.type;
    }
  },
  // 监听页面初次渲染完成
  onReady() {},
  watch: {
    selRegion: {
      handler(selRegion, oldRegion) {
        if (this.isSel) {
          if (this.filter.includes(selRegion[0])) {
            //存在
            if (selRegion[2] == "全部") {
              this.city = selRegion[0];
            } else {
              this.city = selRegion[2];
            }
          } else {
            if (selRegion[2] == "全部") {
              this.city = selRegion[1];
            } else {
              this.city = selRegion[2];
            }
          }
        } else {
          if (this.filter.includes(selRegion[0])) {
            //存在
            this.city = selRegion[0];
            this.defaultRegion = [selRegion[0], "", selRegion[2]];
          } else {
            this.city = selRegion[1];
            this.defaultRegion = selRegion;
          }
        }
        //数据传出去
      },
      immediate: false,
    },
  },
  // 计算属性
  computed: {},
  // 计算方法
  methods: {
    //关闭地址弹窗
    editAddress(item) {
      this.addShow = false;
      this.form = {
        ...this.form,
        ...item,
      };
    },
    xxAddress() {
      // this.xxAddress();
      this.addShow = true;
      let that = this;
      this.addxxAddressItem = {
        Latitude: that.form.Latitude, //经度
        Longitude: that.form.Longitude, //纬度
        Address: that.form.Address, //详细地址
        PcaAddress: "", //区 街道 地址
        //省市区code值
        AreaCode: "",
        CityCode: "",
        ProvinceCode: "",
      };
    },
    handleGetRegion(e, item) {
      //获取到的数据
      this.isSel = true;
      this.selRegion = e;
      // 省
      this.form.ProvinceCode = item[0].value;
      // 市
      this.form.CityCode = item[1].value;
      // 区
      this.form.AreaCode = item[2].value;
      // 省市区 空格隔开 如北京市 市辖区 西城区
      this.form.FullAddress = e.join(" ");
    },

    // xxAddress() {
    // 	let that = this;
    // 	uni.chooseLocation({
    // 		latitude: Number(that.form.Latitude),
    // 		longitude: Number(that.form.Longitude),
    // 		success: function(res) {
    // 			//纬度
    // 			that.form.Latitude = res.latitude;
    // 			//经度
    // 			that.form.Longitude = res.longitude;
    // 			that.form.Address = res.address;
    // 		},
    // 		fail: function(e) {},
    // 	});
    // },

    cxrzxx(e) {
      this.$http.core.tenantgetAudit(e).then((res) => {
        if (res.Success) {
          console.log(res, 222);
          this.yuanglailist = true;
          let dax = "";
          let num = 0;
          this.form = res.Result;
          if (this.form.FullAddress) {
            dax = res.Result.FullAddress.split(" ");
            if (dax.length > 2) {
              this.defaultRegion = [dax[0], dax[1], dax[2]];
            }

            this.filter.forEach((redf) => {
              if (dax.includes(redf) && dax[2] == "全部") {
                num = 1;
                return;
              }
              if (dax.includes(redf) && dax[2] !== "全部") {
                num = 2;
              }
            });
            // 判断直辖市 是否选的全部
            if (num == 1) {
              this.city = dax[0];
            }
            if (num == 2) {
              this.city = dax[2];
            }
            // 非直辖市 是否选的全部
            if (num == 0) {
              if (dax[2] == "全部") {
                this.city = dax[1];
              } else {
                this.city = dax[2];
              }
            }
          }
          // this.city = dzxx[dzxx.length - 1];
          this.form.Address = res.Result.Address;
          this.form.FullAddress = res.Result.FullAddress;

          if (res.Result.License) {
            let ingsrc2 = {
              url: this.srcinge + res.Result.License,
              shujsrc: res.Result.License,
            };
            let daatsrc2 = [];
            daatsrc2.push(ingsrc2);
            this.fileList2 = daatsrc2;
          }

          if (res.Latitude !== 0 && res.Longitude !== 0) {
            this.form.Latitude = this.Latitude;
            this.form.Longitude = this.Longitude;
          }
        }
      });
    },
    getLocationdw() {
      let tabt = this;
      uni.getLocation({
        type: "wgs84",
        success: function (res) {
          console.log(res);
          tabt.Longitude = Math.abs(res.longitude);
          tabt.Latitude = Math.abs(res.latitude);

          if (tabt.form.Latitude) {
            tabt.form.Latitude = tabt.Latitude;
            tabt.form.Longitude = tabt.Longitude;
          }
        },
      });
    },

    codeChange(text) {
      this.tips = text;
    },
    // 获取验证码
    yanzhengma() {
      if (!this.form.ContactPhone) {
        uni.$u.toast("请输入手机号");
        return;
      }
      let email_reg =
        /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
      if (email_reg.test(this.form.ContactPhone)) {
        let obj = {
          PhoneNumber: this.form.ContactPhone,
          Length: 4,
        };
        if (this.$refs.uCode.canGetCode) {
          uni.showLoading({
            title: "正在获取验证码",
          });
          this.$http.core.sendSmsCode(obj).then((res) => {
            uni.hideLoading();
            uni.$u.toast(res.Message);
            // 通知验证码组件内部开始倒计时
            this.$refs.uCode.start();
          });
        } else {
          uni.$u.toast("倒计时结束后再发送");
        }
      } else {
        uni.$u.toast("手机号错误");
      }
    },
    // 上传 图片
    afterRead(file, lists, name) {
      let that = this;
      let tempFilePaths = file.file;
      uni.uploadFile({
        url: this.$config.domain.baseUrl + "/api/core/file/upload",
        filePath: tempFilePaths.url,
        name: "file",
        header: {
          Authorization:
            uni.getStorageSync("access_token").token_type +
            " " +
            uni.getStorageSync("access_token").access_token,
        },
        success: function (res) {
          if (res.statusCode == 200) {
            let data = JSON.parse(res.data);
            if (data.Success) {
              that.form.License = data.Result.Path;
              let oings = {
                url: that.srcinge + data.Result.Path,
                shujsrc: data.Result.Path,
              };
              if (that.fileList2.length > 0) {
                that.fileList2 = [];
              }
              that.fileList2.push(oings);
            }
          }
        },
      });
    },
    // 删除照片
    deletePic(file, lists, name) {
      this.fileList2.splice(file.index, 1);
    },

    // 上传失败
    error() {
      uni.$u.toast("上传失败");
    },

    clicktijiao() {
      if (this.form.State === 1) {
        this.$util.toast("已认证成功");
        return;
      }

      if (!this.form.FullName) {
        uni.$u.toast("请输入企业名称");
        return;
      }

      if (!this.form.FullAddress) {
        uni.$u.toast("请选择注册地址");
        return;
      }
      if (!this.form.Address) {
        uni.$u.toast("请选择详细地址");
        return;
      }

      if (!this.form.ContactName) {
        uni.$u.toast("请输入联系人名字");
        return;
      }

      // if (!this.form.ContactIdCard) {
      // 	uni.$u.toast("请输入证件号");
      // 	return;
      // }

      if (!this.form.ContactPhone) {
        uni.$u.toast("请输入联系人手机号");
        return;
      }
      if (this.form.ContactPhone) {
        var phonereg = 11 && /^((13|14|15|16|17|18|19)[0-9]{1}\d{8})$/;
        if (!phonereg.test(this.form.ContactPhone)) {
          uni.$u.toast("请输入正确手机号");
          return;
        }
      }

      if (!this.form.yzma) {
        uni.$u.toast("请输入验证码");
        return;
      }

      if (!this.form.License) {
        uni.$u.toast("请上传营业执照");
        return;
      }

      if (this.form.FullName) {
        const realnameReg = /^[\u4E00-\u9FA5]{2,}$/;
        if (!realnameReg.test(this.form.FullName)) {
          uni.$u.toast("企业名称最少输入两个汉字");
          return;
        }
      }
      if (this.form.ContactIdCard) {
        var arrExp = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; //加权因子
        var arrValid = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2]; //校验码
        if (/^\d{17}\d|x$/i.test(this.form.ContactIdCard)) {
          var sum = 0,
            idx;
          for (var i = 0; i < this.form.ContactIdCard.length - 1; i++) {
            // 对前17位数字与权值乘积求和
            sum +=
              parseInt(this.form.ContactIdCard.substr(i, 1), 10) * arrExp[i];
          }
          // 计算模（固定算法）
          idx = sum % 11;
          // 检验第18为是否与校验码相等
          if (
            arrValid[idx] == this.form.ContactIdCard.substr(17, 1).toUpperCase()
          ) {
            // callback()
          } else {
            uni.$u.toast("身份证格式有误");
            return;
          }
        } else {
          uni.$u.toast("身份证格式有误");
          return;
        }
      }

      if (!this.form.ContactName) {
        uni.$u.toast("请输入联系人真实姓名");
        return;
      }

      if (this.form.ContactName) {
        const realnameReg = /^[\u4E00-\u9FA5]{2,4}$/;
        if (!realnameReg.test(this.form.ContactName)) {
          uni.$u.toast("请输入2-4个汉字");
          return;
        }
      }
      if (this.form.yzma) {
        const realyzmReg = /^[0-9]*$/;
        if (!realyzmReg.test(this.form.yzma)) {
          uni.$u.toast("验证码只能是数字");
          return;
        }
      }

      if (this.yuanglailist) {
        let objstring = JSON.stringify(this.form);
        let dax = JSON.parse(objstring);
        let isdg = dax.Id;
        // 修改
        this.$http.core.corpupdate(dax, isdg).then((res) => {
          this.$util.toast(res.Message);
          setTimeout((res) => {
            uni.navigateBack({
              delta: 1,
            });
          }, 1000);
        });
      } else {
        let objstring = JSON.stringify(this.form);
        let dax = JSON.parse(objstring);
        let isdg = dax.Id;
        dax.IsCreateCorp = 1;

        // 添加
        this.$http.core.corpadd(dax).then((res) => {
          this.$util.toast(res.Message);

          setTimeout((res) => {
            uni.navigateBack({
              delta: 1,
            });
          }, 1000);
        });
      }
    },
  },
};
</script>

<style scoped lang="scss">
.box {
  padding: 0 30rpx;

  .content {
    // margin-top: 30rpx;
    background: #ffffff;
    border-radius: 20rpx;

    .bodycontent {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx 40rpx;
    }
  }

  .but {
    text-align: center;
    padding: 100rpx 5rpx;

    .tijiao {
      padding: 24rpx 32rpx;
      background-color: #3476fe;
      border-radius: 10rpx;
      color: #ffffff;
      display: inline-block;
      width: 90%;
      font-size: 30rpx;
    }
  }
}

.pre-box {
  margin-top: 20rpx;
  background: #ffffff;
  // text-align: right;
  display: flex;

  .pre-item-image {
    width: 170rpx;
    height: 170rpx;
    margin: 10rpx;
    padding: 10rpx;
  }
}
</style>